using System;
using System.Collections.Generic;
using Edge.Common;
using Edge.Common.ComponentModel;
using Edge.Common.ComponentModel.Notification;
using Edge.Common.Services;
using Edge.Common.Utils;
using Edge.DAL.Common;
using Edge.DAL.Managers;
using NHibernate;
using NHibernate.Expression;
using Shop.Business.Domain.Catalog;
using Shop.Business.Domain.Customers;

namespace Shop.DAL.Managers
{
    class MenuItemManager : AbstractManager<CatalogMenuItem, int, Customer>, IMenuItemManager
    {
        public ICollection<CatalogMenuItem> Find(FetchOptions fetchOptions, MenuItemFilter filter)
        {
            ICriteria criteria = CreateCriteria(fetchOptions);
            AddRestrictions(criteria, filter);
            return criteria.List<CatalogMenuItem>();
        }

        public int Count(MenuItemFilter filter)
        {
            ICriteria criteria = CreateCriteria();
            AddRestrictions(criteria, filter);
            criteria.SetProjection(Projections.RowCount());
            return (int)criteria.List()[0];
        }

        private void AddRestrictions(ICriteria criteria, MenuItemFilter filter)
        {
            if (!StringUtils.IsBlankOrNull(filter.GetText()) && !(filter.GetText().Trim().Equals("")))
            {
                criteria.Add(Expression.Disjunction()
                                 .Add(Expression.Like("Name", "%" + filter.GetText().Trim() + "%"))
                    );
            }
            if (filter.Parent != null)
                criteria.Add(Expression.Eq("Parent", filter.Parent));
            if (!StringUtils.IsBlankOrNull(filter.Query))
            {
                criteria.Add(Expression.Eq("Query", filter.Query));
            }
        }


    }
}